#include "virtual_ide.h"
#include "thread.h"
#include "interrupt.h"
#include "virtual_pic8259a.h"
#include "vmm.h"
#include "print.h"
#include "GP_handler.h"
#include "string.h"

void virtual_ide(void* arg);
void virtual_ide(void* arg) {
   //asm("jmp .");
   while(1) {
      if (virtual_ide_read_state == 0x1) {
         memset((void*)(0xc0055000), 0x0, 512);
         int i = 0;
         while(i < 512) {
            *((uint8_t*)(0xc0055000 + i)) = *((uint8_t*)(0xc0900000 + ((virtual_lba - 210) * 512) + i));
            i++;
         }
         virtual_lba = 0x0;

         virtual_ide_read_state = 0x0;
         ((struct PIC8259A*)((struct vcpu*)(0xc0053000))->pic)->irr |= (1 << 2);
      } 
      else if (virtual_ide_write_state == 0x1) {
         int j = 0;
         while(j < 512) {
            *((uint8_t*)(0xc0900000 + ((virtual_lba - 210) * 512) + j)) = *((uint8_t*)(0xc0055000 + j));
            j++;
         }
         virtual_lba = 0x0;

         virtual_ide_write_state = 0x0;
         memset((void*)(0xc0055000), 0x0, 512);
         ((struct PIC8259A*)((struct vcpu*)(0xc0053000))->pic)->irr |= (1 << 2);
      }
      else {
         asm ("cli");
         schedule();
         asm("sti");
      }
   }
}




void virtual_ide_init(void) {
    thread_start("ide", 10, virtual_ide, "ide");
    put_str("virtual ide init!\n");
}